import { ElMessage } from 'element-plus';
import { getTableList, getTableColumns } from '@/api/data-sync';

// 默认表单值
export const defaultFormValues = {
  task_name: '',
  db_info_setting_id: '',
  table_name: '',
  query_condition: '',
  data_limit: null,
  cron_expression: '0 0 * * * ?',
  status: 0,
  details: [],
  ts_mapping: []
};

// 表单校验规则
export const formRules = {
  task_name: [{ required: true, message: '请输入任务名称', trigger: 'blur' }],
  db_info_setting_id: [{ required: true, message: '请选择数据源', trigger: 'change' }],
  table_name: [{ required: true, message: '请选择表名', trigger: 'change' }],
  cron_expression: [{ required: true, message: '请输入Cron表达式', trigger: 'blur' }],
};

// 获取表列表
export const fetchTables = async (dbId: string) => {
  if (!dbId) return [];
  try {
    const res: any = await getTableList(dbId);
    if (res.code === 200 && res.data) {
      return res.data;
    }
    return [];
  } catch (error) {
    console.error('获取表列表失败:', error);
    ElMessage.error('获取表列表失败');
    return [];
  }
};

// 表名查询建议过滤函数
export const filterTableSuggestions = (tables: string[], queryString: string): { value: string }[] => {
  const results = queryString
    ? tables.filter(item => item.toLowerCase().includes(queryString.toLowerCase()))
    : tables;
  return results.map(item => ({ value: item }));
};

// 获取列名列表
export const fetchColumns = async (dbId: string, tableName: string) => {
  if (!dbId || !tableName) return [];
  try {
    const res: any = await getTableColumns(dbId, tableName);
    if (res.code === 200 && res.data) {
      return res.data;
    }
    return [];
  } catch (error) {
    console.error('获取列名列表失败:', error);
    ElMessage.error('获取列名列表失败');
    return [];
  }
};